package com.guguskins.back.common.schedules;

import com.guguskins.back.common.constant.RedisConstant;
import com.guguskins.back.service.GuSystemConfigService;
import com.guguskins.back.service.GuUserService;
import com.guguskins.back.utils.DateUtil;
import com.guguskins.back.utils.MessageMD5;
import com.guguskins.back.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.Objects;

@Component
public class GuUserSchedule {

    @Autowired
    private GuUserService userService;

    @Autowired
    private GuSystemConfigService systemConfigService;

    @Scheduled(cron = "0 0 0 */1 * ?")
    private void updateUserRevolutionsAndInviteCode() {
        userService.list().forEach(user -> {
            user.setUserRevolutions(0);
            if (!user.getUserInviteExp().toLocalDate().isAfter(LocalDate.now())) {
                user.setUserInviteCode(Objects.requireNonNull(MessageMD5.encrypt(System.currentTimeMillis() + user.getUserNickname())).substring(0, 8));
                user.setUserInviteExp(DateUtil.getTime(systemConfigService.getSystemConfig().getConfigInviteCodeExp()));
            }
            userService.updateById(user);
        });
        RedisUtil.deleteKeys(RedisConstant.FREQUENCY);
        RedisUtil.deleteKeys(RedisConstant.MONEY);
    }
}
